package com.jiantong.work.impl.service;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.work.enums.BreedReportStatus;
import com.jiantong.work.enums.DocumentsDeleteFlag;
import com.jiantong.work.impl.dao.BreedReportDao;
import com.jiantong.work.model.BreedReport;
import com.jiantong.work.service.BreedReportReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.PageInfo;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by niufei on 2017/3/15.
 *
 */
@Slf4j
@Service
@RpcProvider
public class BreedReportReadServiceImpl implements BreedReportReadService{

    private final BreedReportDao breedReportDao;

    @Autowired
    public BreedReportReadServiceImpl(BreedReportDao breedReportDao){
        this.breedReportDao = breedReportDao;
    }

    @Override
    public Response<BreedReport> findById(Long id) {
        try{
            BreedReport breedReport = breedReportDao.findById(id);
            if(breedReport == null){
                log.error("breedReport(id={}) is not found", id);
                return Response.fail("breedReport.not.found");
            }
            return Response.ok(breedReport);
        }catch (Exception e){
            log.error("failed to find breedReport(id={}), cause:{}", id, Throwables.getStackTraceAsString(e));
            return Response.fail("breedReport.find.fail");
        }
    }

    /**
     * 溯源
     * @param breedType 养殖类型
     * @param markNumber 耳标号
     * @return BreedReport
     */
    @Override
    public Response<BreedReport> findByMarkNumber(Integer breedType ,String markNumber) {
        try{
            Map<String , Object> criteria = Maps.newHashMap();
            if(breedType != null) criteria.put("breedType",breedType);
            criteria.put("markNumber",markNumber);
            criteria.put("status", BreedReportStatus.HAS_LICENSE.value());
            criteria.put("deleteFlag",DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(breedReportDao.findByMarkNumber(criteria));
        }catch (Exception e){
            log.error("failed to find breedReport cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("breedReport.find.fail");
        }
    }

    @Override
    public Response<Paging<BreedReport>> pagingBreedReport(Integer pageNo, Integer pageSize, Map<String, Object> criteria) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            return Response.ok(breedReportDao.paging(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("BreedReport.paging.fail");
        }
    }

    @Override
    public String findCurrentMaxNumber(String number) {
        return breedReportDao.findCurrentMaxNumber(number);
    }

    @Override
    public Response<Map<String ,Integer>> findStatusById(Long id) {
        try{
            Integer status = breedReportDao.findStatusById(id);
            if(status == null){
                log.error("BreedReport status(id={}) is not found", id);
                return Response.fail("BreedReport status.not.found");
            }
            Map<String ,Integer> map = Maps.newHashMap();
            map.put("status",status);
            return Response.ok(map);
        }catch (Exception e){
            log.error("failed to find BreedReport status(id={}), cause:{}", id, Throwables.getStackTraceAsString(e));
            return Response.fail("BreedReport status.find.fail");
        }
    }

    @Override
    public Response<Paging<BreedReport>> pagingBreedReportAll(Integer pageNo, Integer pageSize, List<Integer> statuses) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            Map<String, Object> criteria = Maps.newHashMap();
            if(statuses!=null) {
                criteria.put("statuses",statuses);
            }
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(breedReportDao.pagingBreedReport(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("all BreedReport.paging.fail");
        }
    }

    @Override
    public Response<Paging<BreedReport>> pagingMulti(Integer pageNo, Integer pageSize,
                                                     List<Integer> statuses, Long breedFactoryId ,
                                                     Date start , Date end,Integer isScale) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            Map<String, Object> criteria = Maps.newHashMap();

            List<Long> breedFactoryIds = new ArrayList<>();
            if(breedFactoryId != null){
                breedFactoryIds.add(breedFactoryId);
            }else {
                LoginUser loginUser = UserUtil.getCurrentUser();
                breedFactoryIds = loginUser.getBreedFactoryIds();
            }
            if(!breedFactoryIds.isEmpty()) criteria.put("breedFactoryIds",breedFactoryIds);
            else return Response.ok(new Paging<>(0L,new ArrayList<>()));
            if(statuses!=null) {
                criteria.put("statuses",statuses);
            }
            if(start != null){
                criteria.put("start",start);
            }
            if(end != null){
                criteria.put("end",end);
            }

            if(isScale != null){
                criteria.put("isScale",isScale);
            }
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(breedReportDao.pagingMulti(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("all BreedReport.paging.fail");
        }
    }

    /**
     * 分页查询
     *
     * @param pageNo               页码
     * @param pageSize             条数
     * @param statuses             状态集合
     * @param applyReportId
     * @param certificateStationId
     * @param start
     * @param end
     * @param isScale              @return Paging<BreedReport>
     */
    @Override
    public Response<Paging<BreedReport>> pagingMultiGF(Integer pageNo, Integer pageSize, List<Integer> statuses, Long applyReportId, Long certificateStationId, Date start, Date end, Integer isScale) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            Map<String, Object> criteria = Maps.newHashMap();

            List<Long> applyReportIds = new ArrayList<>();
            List<Long> certificateStationIds = new ArrayList<>();
            if(applyReportId != null){
                applyReportIds.add(applyReportId);
            }else {
                LoginUser loginUser = UserUtil.getCurrentUser();
                applyReportIds = loginUser.getDeclareStationIds();
            }

            if (certificateStationId != null){
                certificateStationIds.add(certificateStationId);
            }else {
                LoginUser loginUser = UserUtil.getCurrentUser();
                certificateStationIds = loginUser.getCertificateStationIds();
            }

            if(!applyReportIds.isEmpty()) criteria.put("applyReportIds",applyReportIds);

            if(!certificateStationIds.isEmpty()) criteria.put("certificateStationIds",certificateStationIds);

            if(applyReportIds.isEmpty() && certificateStationIds.isEmpty()){
                return Response.ok(new Paging<>(0L,new ArrayList<BreedReport>()));
            }

            if(statuses!=null) {
                criteria.put("statuses",statuses);
            }
            if(start != null){
                criteria.put("start",start);
            }
            if(end != null){
                criteria.put("end",end);
            }

            if(isScale != null){
                criteria.put("isScale",isScale);
            }
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(breedReportDao.pagingMultiGF(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("all BreedReport.paging.fail");
        }
    }

    /**
     * 通用条件分页查询（criteria）
     * @param pageNo 页码
     * @param pageSize  条数
     * @param criteria  状态集合
     * @return Paging<BreedReport>
     */
    @Override
    public Response<Paging<BreedReport>> pagingCommon(Integer pageNo, Integer pageSize, Map<String, Object> criteria) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(breedReportDao.pagingCommon(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("all BreedReport.paging.fail");
        }
    }
    @Override
    public Response<List<Map>> areaorder(){
        return Response.ok(breedReportDao.areaorder());
    }

    @Override
    public Response<List<Map>> applyorder(){
        return Response.ok(breedReportDao.applyorder());
    }


    @Override
    public Response<Paging<BreedReport>> cert(Integer pageNo, Integer pageSize, Map<String, Object> criteria) {
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            return Response.ok(breedReportDao.cert(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        }catch (Exception e){
            log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("all BreedReport.paging.fail");
        }
    }
    /**
     * 官方兽医 首页
     *
     * @param pageNo          页码
     * @param pageSize        每页多少条
     * @param breedFactoryIds 养殖场IDs
     * @param statuses        状态集合
     * @return
     */
            @Override
            public Response<Paging<BreedReport>> pagingForVeterinarian(Integer pageNo, Integer pageSize, List<Long> breedFactoryIds, List<Integer> statuses) {
                try{
                    PageInfo pageInfo = new PageInfo(pageNo,pageSize);
                    Map<String, Object> criteria = Maps.newHashMap();
                    criteria.put("breedFactoryIds",breedFactoryIds);
                    if(statuses!=null) {
                        criteria.put("statuses",statuses);
                    }
                    criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
                    return Response.ok(breedReportDao.pagingMulti(pageInfo.getOffset(),pageInfo.getLimit(),criteria));

                }catch (Exception e){
                    log.error("failed to paging BreedReport all, cause:{}",Throwables.getStackTraceAsString(e));
                    return Response.fail("all BreedReport.paging.fail");
                }
            }
}
